package org.hyson.gofun;

import java.lang.Thread;
import android.app.AlertDialog.Builder;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.graphics.Point;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.os.Looper;
import android.content.DialogInterface;
import java.io.Serializable;
import android.content.SharedPreferences; 

public class Game extends Activity{

	private final static int board_size = 6;
	private static final String GOFUN_KEY = "GOFUN";
        public static final String PLAYER1_KEY= "com.hyson.gofun.PLAYER1";  
        public static final String PLAYER2_KEY= "com.hyson.gofun.PLAYER2";  
        public static final String BOARD_KEY= "com.hyson.gofun.BOARD";  


	private  GameView game_view;
	private Board  board;
	private Player player1;
	private Player player2;
	private Player cur_player;
	private GameStatus status; 
	private GameStatus save_status; 
	@Override
		public Dialog onCreateDialog(int id){
			switch(id){
				case 0x01:
					AlertDialog.Builder builder = new AlertDialog.Builder(this);
					builder.setMessage("Winner is " + cur_player + "!")
						.setPositiveButton("Back", new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int id) {
								Game.this.finish();
								}
								});
					return builder.create();
			}
			return null;
		}
	private Handler mParentHandler = new Handler(){
		public void handleMessage(Message msg){
			Log.d("Game", "parent handleMessage msg");
			switch(msg.what){
				case 0x01:
					game_view.invalidate();
					break;
				case 0x02:
					showDialog(0x01);
					break;
			}
		}
	};
	public int GameStatus2Int(GameStatus status){
		switch(status){
		case GAME_SET:
		  return 0;
		case GAME_SET_LAST:
	        return 1;
		case GAME_MOVE:
	        return 2;
		case GAME_KILL:
	        return 3;
		case GAME_OVER:
	        return 4;
			
		}
		return 0;
		
	}
	public GameStatus int2GameStatus(int status){
		switch(status){
		case 0:
		  return GameStatus.GAME_SET;
		case 1:
	        return GameStatus.GAME_SET_LAST;
		case 2:
	        return GameStatus.GAME_MOVE;
		case 3:
	        return GameStatus.GAME_KILL;
		case 4:
	        return GameStatus.GAME_OVER;
			
		}
		return GameStatus.GAME_SET;
	}
	@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			game_view = new GameView(this,board_size,board_size);
			setContentView(game_view);

			if(savedInstanceState == null){
				Log.d("Game", "New onCreate");
				board = new Board(board_size,board_size);
				player1 = PlayerFactory.createPlayer(1, Pieces.P1, (board_size *board_size)/2, true,board,this);
				player2 = PlayerFactory.createPlayer(2, Pieces.P2, (board_size *board_size)/2, false,board,this);
				cur_player = player1;
				status = GameStatus.GAME_SET;
				save_status = GameStatus.GAME_SET;
			}else{
				Log.d("Game", "reStore onCreate");
				Bundle map = savedInstanceState.getBundle(GOFUN_KEY);
			        if (map != null) {
			     		player1 = (Player)map.getSerializable(PLAYER1_KEY);  
			     		player2 = (Player)map.getSerializable(PLAYER2_KEY);  
			     		board = (Board)map.getSerializable(BOARD_KEY);  
					status = int2GameStatus(map.getInt("status"));
					save_status = int2GameStatus(map.getInt("save_status"));
					if(map.getInt("player_index") == 0){
						cur_player = player1;
					}
					if(map.getInt("player_index") == 1){
						cur_player = player2;
					}
				 }

			}
			mThread.start();
		}
		  protected void onPause() {
		         super.onPause();
		
		}
	public void onSaveInstanceState(Bundle outState) {
/*
		Log.d("Game", "onSaveInstanceState");
        Bundle map = new Bundle();
		map.putSerializable(PLAYER1_KEY,player1);  
		map.putSerializable(PLAYER2_KEY,player2);  
		map.putSerializable(BOARD_KEY,board);  
		map.putInt("status", Integer.valueOf(GameStatus2Int(status)));
		map.putInt("save_status", Integer.valueOf(GameStatus2Int(save_status)));
		if(cur_player == player1){
	        	map.putInt("player_index", 0);
		}
		if(cur_player == player2){
	        	map.putInt("player_index", 1);
		}
	        outState.putBundle(GOFUN_KEY, map);
*/
	}
	public GameStatus getStatus(){
		return status;
	}
	public Player getRivalPlayer(){
		if(player2.getWho()  == cur_player.getWho())
			return player1;
		if(player1.getWho()  == cur_player.getWho())
			return player2;

		return player1;
	}
	public void chgPlayer(){
		if(player2.getWho()  == cur_player.getWho()){
			cur_player = player1;
			return ;
		}
		if(player1.getWho()  == cur_player.getWho()){
			cur_player = player2;
			return ;
		}
	}
	public Player getCurPlayer(){
		return cur_player;
	}
	public void gameOver(){
		Message msg = this.mParentHandler.obtainMessage();
		msg.what = 0x02;
		this.mParentHandler.sendMessage(msg);
	}
	public void sendUpdate(){
		Message msg = this.mParentHandler.obtainMessage();
		msg.what = 0x01;
		this.mParentHandler.sendMessage(msg);
	}
	public Board getBoard(){
		return board;
	}
	public boolean doNextStep(){
		int kill_num = 0;
		Pieces lose_player;
		boolean chg_player = false;
		Point set_pos = new Point();
		Point kill_pos= new Point();
		Point src_pos = new Point();
		Point dst_pos = new Point();
		switch(status){
			case GAME_SET:
				Log.d("Game", "Now is GAME_SET");
				cur_player.getNextSet(set_pos);//获取下一步
				if(board.getPos(set_pos) != Pieces.EMPTY)
					break;
				board.setCurPoint(set_pos);
				board.setPieces(set_pos, cur_player.getWho());
				kill_num = board.getKills(set_pos, cur_player.getWho());//是否有杀
				if(cur_player.decFreePieces()){
					kill_num++;
					save_status = GameStatus.GAME_SET;
					if(cur_player.getWho() == Pieces.P2){
						save_status = GameStatus.GAME_SET_LAST;
						status = GameStatus.GAME_KILL;
						cur_player.setKillNum(kill_num);
						cur_player.setKillWho(getRivalPlayer().getWho());
						break;
					}
				}
				if(kill_num > 0){
					save_status  = GameStatus.GAME_SET;
					status = GameStatus.GAME_KILL;
					cur_player.setKillNum(kill_num);
					cur_player.setKillWho(getRivalPlayer().getWho());
				}else{
					chg_player = true;
				}
				break;
			case GAME_KILL:
				Log.d("Game", "Now is GAME_KILL");
				cur_player.getNextKill(kill_pos);//获取下一步
				if(board.getPos(kill_pos) != cur_player.getKillWho()){
					break;
				}
				board.setCurPoint(kill_pos);
				board.killPieces(kill_pos, save_status);
				if((lose_player = board.noPieces()) != Pieces.NO && save_status != GameStatus.GAME_SET){
					if(lose_player == Pieces.P2){
						cur_player = player1;
					}
					if(lose_player == Pieces.P1){
						cur_player = player2;
					}
					status = GameStatus.GAME_OVER;
					break;
				}
				cur_player.decKillNum();
				if(cur_player.getKillNum() == 0){
					status = save_status;
					chg_player = true;
				}
				break;
			case GAME_SET_LAST:
				Log.d("Game", "Now is GAME_SET_LAST");
				board.cleanForbid();
				status = GameStatus.GAME_MOVE;
				break;
			case GAME_MOVE:
				Log.d("Game", "Now is GAME_SET_MOVE");
				if(cur_player.getNextMove(src_pos, dst_pos)){
					Log.d("Game", "src_pos = " + src_pos.x + " " + src_pos.y );
					Log.d("Game", "dst_pos = " + dst_pos.x + " " + dst_pos.y );
					getBoard().setPos(src_pos.x, src_pos.y, getCurPlayer().getWho());
					if(!board.movePieces(src_pos, dst_pos, cur_player.getWho())){
							Log.d("Game", "Can not  move");
							break;
					}
					board.setCurPoint(dst_pos);
					Log.d("Game", "Can move");
					kill_num = board.getKills(dst_pos, cur_player.getWho());//是否有杀
					if(kill_num > 0){
						save_status = status;
						status = GameStatus.GAME_KILL;
						cur_player.setKillNum(kill_num);
						cur_player.setKillWho(getRivalPlayer().getWho());
					}else{
						chg_player = true;
					}
				}else{
					cur_player.setKillNum(1);
					cur_player.setKillWho(cur_player.getWho());
				}
				break;
			case GAME_OVER:
				break;
		}
		if(chg_player)
			chgPlayer();
		return chg_player;
	}
	//控制线程 控制整个游戏流程
	final Thread mThread = new Thread() {
		@Override
			public void run(){
				while(status != GameStatus.GAME_OVER){ 
					Log.d("Game", "I am " + cur_player);
					while(!cur_player.thinkOver()){
						try
						{   
							Thread.sleep(100);
						}
						catch(Exception e){} 
					}
					doNextStep();
					sendUpdate();//发送消息更新UI
				}
				gameOver();//发送消息结束游戏
			}

	};
}

